// request.js
// 定义接口的基础 URL
const baseURL = 'http://admin.bsmall.byesame.com/wx/';

// 封装请求方法
const request = (options) => {
    return new Promise((resolve, reject) => {
        // 合并默认配置和传入的配置
        const defaultOptions = {
            url: baseURL + options.url,
            method: options.method || 'GET',
            data: options.data || {},
            header: {
                'Content-Type': 'application/json',
                ...options.header
            },
            success: (res) => {
                // console.log(res,'封装的res');
                if (res.statusCode === 200) {
                    // 请求成功，返回响应数据
                    resolve(res);
                } else {
                    // 请求失败，显示错误信息并拒绝 Promise
                    uni.showToast({
                        title: `请求出错，状态码: ${res.statusCode}`,
                        icon: 'none'
                    });
                    reject(new Error(`请求出错，状态码: ${res.statusCode}`));
                }
            },
            fail: (err) => {
                // 请求失败，显示错误信息并拒绝 Promise
                uni.showToast({
                    title: '请求失败，请检查网络',
                    icon: 'none'
                });
                reject(err);
            }
        };
        // 发起请求
        uni.request(defaultOptions);
    });
};

// 封装常用的请求方法
const api = {
    get(url, data = {}, header = {
        "x-byesame-token": uni.getStorageSync('Authorization')
    }) {
        return request({ url, method: 'GET', data, header });
    },
    post(url, data = {}, header = {
        "x-byesame-token": uni.getStorageSync('Authorization')
    }) {
        return request({ url, method: 'POST', data, header });
    },
    put(url, data = {}, header = {
        "x-byesame-token": uni.getStorageSync('Authorization')
    }) {
        return request({ url, method: 'PUT', data, header });
    },
    delete(url, data = {}, header = {
        "x-byesame-token": uni.getStorageSync('Authorization')
    }) {
        return request({ url, method: 'DELETE', data, header });
    }
};

export default api;